package com.heyige.service.ai;

import com.heyige.dto.ChatDto;
import com.heyige.exception.BusinessException;
import com.heyige.exception.ErrorCode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.deepseek.DeepSeekAssistantMessage;
import org.springframework.ai.deepseek.DeepSeekChatModel;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class DeepSeekService implements AiModelService {

    private final DeepSeekChatModel chatModel;

    @Override
    public ChatDto.ChatResponse chat(ChatDto.ChatRequest request) {
        long startTime = System.currentTimeMillis();
        try {
            // 构建系统提示词
            StringBuilder systemPrompt = new StringBuilder();
            if (request.getSystemPrompt() != null && !request.getSystemPrompt().isEmpty()) {
                for (String prompt : request.getSystemPrompt()) {
                    systemPrompt.append(prompt).append("\n");
                }
            } else {
                systemPrompt.append("你是一个智能助手，请根据用户的问题提供有帮助的回答。");
            }
            // 创建提示词
            UserMessage userMessage = new UserMessage(request.getContent());
            Message assistantMessage = DeepSeekAssistantMessage.prefixAssistantMessage(systemPrompt.toString());
            Prompt prompt = new Prompt(List.of(userMessage, assistantMessage));
            // 调用模型
            ChatResponse response = chatModel.call(prompt);
            // 获取结果
            String content = response.getResult().getOutput().getText();
            // 获取token使用量（如果可用）
            Integer tokens = 0;
            if (response.getMetadata().getUsage() != null) {
                tokens = response.getMetadata().getUsage().getTotalTokens();
            }

            // 构建响应
            ChatDto.ChatResponse chatResponse = new ChatDto.ChatResponse();
            chatResponse.setContent(content);
            chatResponse.setModel(getModelName());
            chatResponse.setTokens(tokens);
            chatResponse.setResponseTime(System.currentTimeMillis() - startTime);
            log.info("DeepSeek模型调用成功，耗时: {}ms", System.currentTimeMillis() - startTime);
            return chatResponse;
        } catch (Exception e) {
            log.error("DeepSeek模型调用异常", e);
            throw new BusinessException(ErrorCode.CHAT_MODEL_CALL_FAILED, "DeepSeek模型调用异常: " + e.getMessage());
        }
    }

    @Override
    public String getModelName() {
        return "deepseek-chat";
    }

    @Override
    public boolean isAvailable() {
        try {
            // 简单的健康检查
            String response = chatModel.call("请回复'OK'");
            return response != null;
        } catch (Exception e) {
            log.error("DeepSeek模型可用性检查失败", e);
            return false;
        }
    }

    @Override
    public int getPriority() {
        return 2; // 第二优先级
    }
}